﻿using Powershell_ML;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;

namespace Collectorsvc
{
    class Program
    {
        public static PowerShell_Instance Runner = new PowerShell_Instance();
        static PSObject Get_Mailbox = Runner.Execute_Command_Once(Const.Get_OrganizationConfig);
        static Organization_Configuration Test = new Organization_Configuration(Get_Mailbox);
        static Configuration Manager = new Configuration();
        public delegate void EventHandler();
        public static event EventHandler _show;
        public static event EventHandler _MaintenanceStarter;
        static int Collection_Count = 0;
        static void Main(string[] args)
        {

            _show += new EventHandler(Recurent);
            _MaintenanceStarter += new EventHandler(Check_Usage);
            _MaintenanceStarter.Invoke();
            _show.Invoke();
            
        }
        protected virtual void Checusage()
        {
            Check_Usage();
        }
        static void Check_Usage()
        {

            try
            {
                string[] allfiles = System.IO.Directory.GetFiles(System.IO.Directory.GetCurrentDirectory(), "*.xml");
                foreach (string found in allfiles)
                {
                    System.IO.FileInfo Informations = new System.IO.FileInfo(found);
                    if (Informations.CreationTime < DateTime.Now.AddMonths(-3))
                    {
                        Informations.Delete();
                    }
                }
            }
            catch { }

        }
        static void Recurent()
        {
            while (true)
            {
                Console.WriteLine("Collecting Stats..");
                List<Thread> ToDo = new List<Thread>();
                if (Manager.ServerMonitor.Count > 0)
                {
                    foreach (string server in Manager.ServerMonitor)
                    {

                        System.Threading.Thread Thread_Collector = new System.Threading.Thread
                        (delegate ()
                        {
                            Server Exchange_Server = Test.Get_ExchangeServer_ByName(server);
                            Console.WriteLine("Thread Started for : {0}", server);
                            Collection_Count++;
                            ManualResetEvent syncEvent = new ManualResetEvent(false);
                            List<Queue> MDBT = new List<Queue>();
                            
                            List<MailboxDatabase> MDBL = new List<MailboxDatabase>();
                            if (Test.isMailbox(server))
                            {
                                List<Mailbox> MDBX = Test.Mailbox_ByServer(server);
                                Test.Mailbox_Export_Stats(MDBX);
                                MDBL = Test.MailboxDatabase_ByServer(server);
                                Test.MailboxDatabase_Export_Stats(MDBL);
                                MDBL.OrderBy(o => o.Collected_Date).ToList();
                            }
                            if(Test.IsTransport(server))
                            {
                                MDBT = Test.TransportQueue_byServer(server);
                                Test.Export_TMQUEUE(MDBT);
                            }
                            if(Collection_Count > 0 & Test.IsOdd(Collection_Count) & MDBL.Count > 0)
                            {
                                Test.MDB_Update_Stats(MDBL);
                            }
                        });
                        ToDo.Add(Thread_Collector);
                    }
                    ToDo.ToList().ForEach(x =>
                    {
                        x.IsBackground = true;
                        x.Start();
                        var watch = Stopwatch.StartNew();
                        while (x.IsAlive)
                        {
                            Console.WriteLine("Collection Thread Running Since  : {0}", watch.Elapsed);
                            Thread.Sleep(1000);
                        }
                        watch.Stop();
                    Console.WriteLine("Thread Taken : {0}", watch.Elapsed);
                    });
                    Console.WriteLine("Collection Threads Finished..");
                }
                Wait_For(Manager.CollectFrequency);
            }
        }
        static void Wait_For(TimeSpan mil)
        {
            Console.WriteLine("Waiting for Next Collection..");
            System.Threading.Thread Maintenance = new System.Threading.Thread
            (delegate ()
            {
                Check_Usage();
            });
            Maintenance.Start();
            Maintenance.Join();
            Thread.Sleep(45000);
            Console.WriteLine("New Collection Started At : {0}", DateTime.Now);
            Recurent();
        }
        static void Application_Start()
        {
            Thread thread = new Thread(new ThreadStart(ThreadFunc));
            thread.IsBackground = false;
            thread.Name = "ThreadFunc";
            thread.Start();
            thread.Join();
        }

        static void ThreadFunc()
        {
            System.Timers.Timer t = new System.Timers.Timer();
            t.Elapsed += new System.Timers.ElapsedEventHandler(TimerWorker);
            t.Interval = 300;
            t.Enabled = true;
            t.AutoReset = true;
            t.Start();
        }

        static void TimerWorker(object sender, System.Timers.ElapsedEventArgs e)
        {
                if(Manager.ServerMonitor.Count >0)
                { 
                    foreach (string server in Manager.ServerMonitor)
                    {
                        List<MailboxDatabase> MDBL = new List<MailboxDatabase>();
                        MDBL = Test.MailboxDatabase_ByServer(server);
                        Test.MailboxDatabase_Export_Stats(MDBL);
                        MDBL.OrderBy(o => o.Collected_Date).ToList();
                    }
                }
        }
    }
}
